Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '',
    currentDate: Date.now(),
    maxDate: Date.now() + 3 * 24 * 60 * 60 * 1000,
    // -----------------------
    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '',
  },
  onLoad() {
    // 获取房屋列表
    this.getHouseList()
  },
  async getHouseList() {
    // 请求数据接口
    const { code, data: houseList } = await wx.http.get('/house')
    // 检测接口返回的结果
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败!')
    // 数据渲染
    this.setData({ houseList })
  },

  // ------------------------
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  selectHouse(e) {
    const { id: houseId, name: houseInfo } = e.detail
    this.setData({
      houseId,
      houseInfo,
    })
  },
  // -------------------------

  // --------------------------
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  selectDate(e) {
    this.setData({
      visitDate: wx.utils.formatDate(e.detail),
      dateLayerVisible: false,
    })
  },
  // -----------------------------

  async goPassport() {
    const { houseId, name, mobile, visitDate, gender } = this.data
    // 1. 校验
    if (!wx.utils.verifyHouse(houseId)) return
    if (!wx.utils.verifyName(name)) return
    if (!wx.utils.verifyMobile(mobile)) return
    if (!wx.utils.verifyDate(visitDate)) return

    // 2. 调用接口
    // 请求接口
    const { code, data } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    // 检测接口调用结果
    if (code !== 10000) return wx.utils.toast('添加访客失败!')

    // wx.navigateTo 压栈操作
    // wx.redirectTo 压栈操作, 但是会从页面栈中移除当前页面对象
    // wx.reLaunch 压栈操作 会移除页面栈中所有的页面对象
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  },
})
